// 本地刷新token，保证接口请求不过期
import storage from '@/utils/ado-self/ado-storage';
import login from 'lib/local/login.js';
const tokenKey = 'visual_components_token';

// -------------------- 函数

// 刷新token
function reFreshToken(env) {
  return new Promise(async resolve => {
    const { envConf } = window.envInfo;
    const { baseUrl, useRemoteToken } = envConf[env];
    const host = baseUrl.replace(/http(s?):\/\/([^\/]+).*/, '$2');

    // 通过登录接口获取token（需要在移动端小蜜蜂app登录时授权隐私协议，得到的token才能在pc用于其他接口连接）
    const tokenByApi = await login.getTokenByAppLogin();
    const userInfo = await login.getWho(tokenByApi);
    const tenant = (userInfo && userInfo.tenants && userInfo.tenants[0]) || {};

    const tokenObj = {
      tenantId: tenant.tenantId,
      clientCode: tenant.clientId,
      ucCode: '',
      pageId: '',
      token: tokenByApi,
    };

    // 通过远程tamperMonkey工具保存到本地public_node_modules的token, tennatId, pageId信息
    const tokens = await login.getEnvTokens();
    if (tokens) {
      const item = tokens[host];
      if (item) {
        tokenObj.tenantId = item.tenantId;
        tokenObj.clientCode = item.clientCode;
        tokenObj.ucCode = item.ucCode;
        tokenObj.pageId = item.pageId;
        tokenObj.platformName = item.platformName;
        tokenObj.pageUrl = item.pageUrl;
        tokenObj.type = item.type;
        if (useRemoteToken && item.token) {
          tokenObj.token = item.token;
        }
      }
    }

    // 将信息存入localstorage
    window._adoPremise.tenantId = tokenObj.tenantId;
    const info = {
      reFreshTime: new Date().getTime(),
      env: env,
      token: tokenObj,
    };
    storage.set(tokenKey, info);
    resolve(info);
  });
}

function initEnvInfo() {
  return new Promise(async resolve => {
    const envInfo = await login.getEnvInfo();

    const storeInfo = storage.get(tokenKey);
    let { env } = storeInfo || {};
    if (env) {
      envInfo.env = env;
    } else {
      env = envInfo.env;
    }
    window.envInfo = envInfo;
    window.visualEnv = env;
    window.visualBaseUrl = envInfo.envConf[env].baseUrl;
    resolve(envInfo);
  });
}

// -------------------- 执行
(async() => {
  await initEnvInfo();
  window.reFreshToken = reFreshToken;
})();
